package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.RegistRes;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@Api(tags = "用户管理")
@RequestMapping("/user/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);
        try {
            User user = userService.login(userLoginDTO);
            Map<String, Object> map = new HashMap<>();
            map.put(JwtClaimsConstant.USER_ID, user.getId());
            String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);
            UserLoginVO userloginVO = UserLoginVO.builder().token(token).id(user.getId()).build();
            return Result.success(userloginVO);
        } catch (Exception e) {
            return Result.error("登录失败");
        }
    }

    @ApiOperation("用户退出")
    @PostMapping("/logout")
    public Result logout() {
        return Result.success();
    }

    @ApiOperation("用户注册")
    @PostMapping("/regist")
    public Result regist(@RequestBody UserLoginDTO userLoginDTO) {
        Boolean flag = userService.regist(userLoginDTO);
        RegistRes r = new RegistRes();
        if (flag) {
            r.setRes(1);
        } else {
            r.setRes(2);
        }
        return Result.success(r);
    }


}
